import React, { useState } from 'react'
import styles from '@/common_components/header/index.module.scss'
import messagePng from './assets/message.png'
import { message, Avatar, Dropdown, Modal, Form, Input } from 'antd'
import type { MenuProps } from 'antd'
import { useNavigate } from 'react-router-dom'
import { LogoutPost, postUpdatePassword } from '@/util/request'
import { useAppDispatch, useAppSelector } from '@/store'
import { set_user_info } from '@/store/slice/user'
import { select_user_info } from '@/store/slice/user/select'
import avatar from './assets/me.jpg'
import { imgUrl } from '@/util/constant'
import CryptoJS from 'crypto-js'

export default function Header() {
  // 控制模态框显示和隐藏的状态
  const [isModalVisible, setIsModalVisible] = useState(false)
  // 表单实例，用于管理表单数据
  const [form] = Form.useForm()

  // 全局提示
  const [messageApi, contextHolder] = message.useMessage()

  const navigate = useNavigate()

  const dispatch = useAppDispatch()
  const userinfo = useAppSelector(select_user_info)

  // 弹出框的内容
  // const popover_content = <div>你的考试已经被批阅</div>

  // 退出登录 清除仓库中的用户信息和localStorage中的信息
  async function handleLogout() {
    // console.log(11111)
    await LogoutPost()
    localStorage.removeItem('menu')
    localStorage.removeItem('topic')
    dispatch(set_user_info({}))
    navigate('/login')
  }

  // 前往个人中心
  const goPersonInfo = () => {
    navigate('/person_info')
  }

  // 打开修改密码的Modal框
  const goUpdatePassword = () => {
    setIsModalVisible(true)
  }

  // Dropdown的信息
  const items: MenuProps['items'] = [
    {
      key: 'user',
      label: <div onClick={goPersonInfo}>个人中心</div>
    },
    {
      key: 'update_password',
      label: <div onClick={goUpdatePassword}>修改密码</div>
    },
    {
      key: 'logout',
      label: <div onClick={handleLogout}>退出登录</div>
    }
  ]

  // 前往主页
  function goHome() {
    if (userinfo.role === 'student') {
      navigate('/exam_select')
    } else {
      navigate('/corret_exam_list')
    }
  }

  // 修改密码的确认按钮
  const handleUpdateConfirm = async () => {
    form
      .validateFields()
      .then(async values => {
        const old_password: string = CryptoJS.AES.encrypt(values.old_password, 'yujian').toString()
        const new_password: string = CryptoJS.AES.encrypt(values.new_password, 'yujian').toString()

        const res = await postUpdatePassword({
          old_password,
          new_password
        })

        if (res.code == 200) {
          messageApi.open({
            type: 'success',
            content: res.data
          })
          form.resetFields()
          setIsModalVisible(false)
        } else {
          messageApi.open({
            type: 'error',
            content: res.data
          })
        }
      })
      .catch(errorInfo => {
        messageApi.open({
          type: 'warning',
          content: '你还有未填写的信息'
        })
        // 有字段验证失败，处理错误信息
        console.log('验证失败:', errorInfo)
      })
  }

  return (
    <>
      {contextHolder}
      <div className={styles.header}>
        {/* logo */}
        <div className={styles.logo} onClick={goHome}>
          {/* <img src={logo} alt="" /> */}
          <h2>考试管理系统</h2>
        </div>
        {/* 信息 */}
        <div className={styles.info}>
          {/* 消息框 */}
          {/* <div className={styles.message}>
          <Popover placement="topRight" content={popover_content} title="提示">
            <img src={messagePng} alt="" />
          </Popover>
        </div> */}
          {/* 空div 占位置 */}
          <div></div>
          {/* 头像和名字 */}
          <div className={styles.avator}>
            <Dropdown menu={{ items }} placement="bottomLeft" arrow>
              <Avatar size={40} src={imgUrl + userinfo.avatar} />
            </Dropdown>
            <div className={styles.name}>{userinfo?.name}</div>
          </div>
        </div>
      </div>

      <Modal
        title="修改密码"
        open={isModalVisible}
        onOk={handleUpdateConfirm}
        onCancel={() => {
          form.resetFields()
          setIsModalVisible(false)
        }}
      >
        {/* Modal表单，用于输入笔记信息 */}
        <Form form={form} layout="vertical">
          <Form.Item name="old_password" label="原密码" rules={[{ required: true, message: '请输入原密码' }]}>
            <Input.Password />
          </Form.Item>
          <Form.Item name="new_password" label="新密码" rules={[{ required: true, message: '请输入新密码!' }]}>
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
